// src/pages/Register.tsx
import React, { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { authApi } from '../../api/auth';
import '../../styles/Auth.css';

const Register = () => {
  const [username, setUsername] = useState('');
  const [phone, setPhone] = useState('');
  const [smsCode, setSmsCode] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [birthDate, setBirthDate] = useState('2005-04-08');
  const [error, setError] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const navigate = useNavigate();

  const handleSendCode = async () => {
    if (!phone) {
      setError('请输入手机号');
      return;
    }
    try {
      await authApi.sendVerificationCode({ phone });
      setCountdown(60);
      const timer = setInterval(() => {
        setCountdown((prev) => (prev > 0 ? prev - 1 : 0));
        if (countdown === 0) clearInterval(timer);
      }, 1000);
    } catch (err) {
      setError('验证码发送失败');
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (password !== confirmPassword) {
      setError('两次密码输入不一致');
      return;
    }
    setIsLoading(true);
    try {
      // console.log(5461);
      
      const res = await authApi.register({
        phone,
        username,
        password,
        birthDate,
      });
      localStorage.setItem('token', res.data.accessToken);
      localStorage.setItem('refreshToken', res.data.refreshToken);
      navigate('/login');
    } catch (err) {
      (err instanceof Error)?err.message:
      (typeof err === 'object' && err !== null && 'message' in err)?
      String(err.message):
      '未知错误'
    //   setError('注册失败: ' + (err.response?.data?.message || err.message));
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="huawei-auth-container">
      <h1 className="huawei-title">华为账号注册</h1>
      
      <div className="huawei-existing-account">
        <Link to="/login">已有账号，去登录</Link>
      </div>

      <form onSubmit={handleSubmit}>
        <div className="huawei-input-group">
          <label>国家/地区</label>
          <div className="huawei-static-value">中国</div>
        </div>

        <div className="huawei-input-group">
          <label>手机号</label>
          <div className="huawei-phone-input">
            <span className="huawei-country-code">+86(中国)</span>
            <input
              type="tel"
              placeholder="请输入手机号"
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              required
            />
          </div>
        </div>
        <div className="huawei-input-group">
          <label>用户名</label>
          <div className="huawei-phone-input">
            {/* <span className="huawei-country-code">+86(中国)</span> */}
            <input
              type="tel"
              placeholder="请输入用户名"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              required
            />
          </div>
        </div>

        {/* <div className="huawei-input-group with-code">
          <label>短信验证码</label>
          <div className="huawei-code-input">
            <input
              type="text"
              placeholder="请输入验证码"
              value={smsCode}
              onChange={(e) => setSmsCode(e.target.value)}
              required
            />
            <button
              type="button"
              className="huawei-code-btn"
              onClick={handleSendCode}
              disabled={countdown > 0}
            >
              {countdown > 0 ? `${countdown}秒后重试` : '获取验证码'}
            </button>
          </div>
        </div> */}

        <div className="huawei-input-group">
          <label>密码</label>
          <input
            type="password"
            placeholder="请输入密码"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
          />
        </div>

        <div className="huawei-input-group">
          <label>确认密码</label>
          <input
            type="password"
            placeholder="请再次输入密码"
            value={confirmPassword}
            onChange={(e) => setConfirmPassword(e.target.value)}
            required
          />
        </div>

        <div className="huawei-input-group">
          <label>出生日期</label>
          <input
            type="date"
            value={birthDate}
            onChange={(e) => setBirthDate(e.target.value)}
            required
          />
        </div>

        {error && <div className="huawei-error">{error}</div>}

        <button
          type="submit"
          className="huawei-primary-btn"
          disabled={isLoading}
        >
          {isLoading ? '注册中...' : '注册'}
        </button>
      </form>
    </div>
  );
};

export default Register;